package leetcode;


import com.alibaba.fastjson.JSON;
import common.TreeNode;

import java.util.*;

/**
 * 二叉树的中序遍历
 */
public class LeetCode94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;
        while (curr != null || !stack.empty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            result.add(curr.val);
            curr = curr.right;
        }
        return result;
    }

    public List<Integer> inorderTraversal1(TreeNode root, List<Integer> result) {
        if (root == null) {
            return result;
        }
        inorderTraversal1(root.left, result);
        result.add(root.val);
        inorderTraversal1(root.right, result);
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode n1 = new TreeNode(2);
        TreeNode n2 = new TreeNode(3);
        TreeNode n3 = new TreeNode(4);
        root.right = n3;
        root.left = n2;
        n2.left = n1;
        LeetCode94 leetCode94 = new LeetCode94();
        System.out.println(JSON.toJSONString(leetCode94.inorderTraversal(root)));
        System.out.println(JSON.toJSONString(leetCode94.inorderTraversal1(root, new ArrayList<>())));
    }

}